{% extends 'base.html' %}
{% load static %}

{% block title %}资产盘点 - {{ item.asset.name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-check-circle me-2"></i>资产盘点 - {{ item.asset.name }}
                        <small class="text-muted ms-2">({{ item.plan.name }})</small>
                    </h5>
                </div>
                
                <div class="card-body">
                    <form method="post" id="inventoryCheckForm">
                        {% csrf_token %}
                        
                        <div class="row">
                            <!-- 资产基本信息 -->
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>资产基本信息</h6>
                                    </div>
                                    <div class="card-body">
                                        <table class="table table-borderless table-sm">
                                            <tr>
                                                <td width="100"><strong>资产名称：</strong></td>
                                                <td>{{ item.asset.name }}</td>
                                            </tr>
                                            <tr>
                                                <td><strong>资产编号：</strong></td>
                                                <td><code>{{ item.asset.asset_number }}</code></td>
                                            </tr>
                                            <tr>
                                                <td><strong>资产类别：</strong></td>
                                                <td>{{ item.asset.category.name }}</td>
                                            </tr>
                                            <tr>
                                                <td><strong>采购价格：</strong></td>
                                                <td>¥{{ item.asset.purchase_price|floatformat:2 }}</td>
                                            </tr>
                                            <tr>
                                                <td><strong>启用日期：</strong></td>
                                                <td>{{ item.asset.purchase_date }}</td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 系统记录信息 -->
                            <div class="col-md-6">
                                <div class="card mb-4">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-database me-2"></i>系统记录信息</h6>
                                    </div>
                                    <div class="card-body">
                                        <table class="table table-borderless table-sm">
                                            <tr>
                                                <td width="100"><strong>系统状态：</strong></td>
                                                <td>
                                                    <span class="badge bg-info">{{ item.get_system_status_display }}</span>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><strong>系统位置：</strong></td>
                                                <td>
                                                    {% if item.system_location %}
                                                        {{ item.system_location.name }}
                                                    {% else %}
                                                        未设置
                                                    {% endif %}
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><strong>系统使用人：</strong></td>
                                                <td>
                                                    {% if item.system_user %}
                                                        {{ item.system_user.get_full_name|default:item.system_user.username }}
                                                    {% else %}
                                                        未分配
                                                    {% endif %}
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><strong>系统部门：</strong></td>
                                                <td>
                                                    {% if item.system_department %}
                                                        {{ item.system_department.name }}
                                                    {% else %}
                                                        未分配
                                                    {% endif %}
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><strong>盘点状态：</strong></td>
                                                <td>
                                                    {% if item.status == 'pending' %}
                                                        <span class="badge bg-secondary">{{ item.get_status_display }}</span>
                                                    {% elif item.status == 'in_progress' %}
                                                        <span class="badge bg-primary">{{ item.get_status_display }}</span>
                                                    {% elif item.status == 'completed' %}
                                                        <span class="badge bg-success">{{ item.get_status_display }}</span>
                                                    {% endif %}
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 盘点结果录入 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h6 class="mb-0"><i class="fas fa-clipboard-check me-2"></i>盘点结果录入</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="physical_status" class="form-label">实际状态 <span class="text-danger">*</span></label>
                                            <select class="form-select" id="physical_status" name="physical_status" required>
                                                <option value="">请选择实际状态</option>
                                                {% for value, label in asset_status_choices %}
                                                    <option value="{{ value }}" {% if value == item.physical_status %}selected{% endif %}>
                                                        {{ label }}
                                                    </option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="physical_location" class="form-label">实际位置</label>
                                            <select class="form-select" id="physical_location" name="physical_location">
                                                <option value="">请选择实际位置</option>
                                                {% for location in locations %}
                                                    <option value="{{ location.id }}" {% if item.physical_location and location.id == item.physical_location.id %}selected{% endif %}>
                                                        {{ location.name }}
                                                    </option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="physical_user" class="form-label">实际使用人</label>
                                            <select class="form-select" id="physical_user" name="physical_user">
                                                <option value="">请选择实际使用人</option>
                                                {% for user in users %}
                                                    <option value="{{ user.id }}" {% if item.physical_user and user.id == item.physical_user.id %}selected{% endif %}>
                                                        {{ user.get_full_name|default:user.username }}
                                                        {% if user.userprofile.department %}
                                                            ({{ user.userprofile.department.name }})
                                                        {% endif %}
                                                    </option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="physical_department" class="form-label">实际部门</label>
                                            <select class="form-select" id="physical_department" name="physical_department">
                                                <option value="">请选择实际部门</option>
                                                {% for department in departments %}
                                                    <option value="{{ department.id }}" {% if item.physical_department and department.id == item.physical_department.id %}selected{% endif %}>
                                                        {{ department.name }}
                                                    </option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="discrepancy_type" class="form-label">差异类型</label>
                                            <select class="form-select" id="discrepancy_type" name="discrepancy_type">
                                                {% for value, label in discrepancy_choices %}
                                                    <option value="{{ value }}" {% if value == item.discrepancy_type %}selected{% endif %}>
                                                        {{ label }}
                                                    </option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label for="status" class="form-label">盘点状态</label>
                                            <select class="form-select" id="status" name="status">
                                                {% for value, label in status_choices %}
                                                    <option value="{{ value }}" {% if value == item.status %}selected{% endif %}>
                                                        {{ label }}
                                                    </option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="discrepancy_notes" class="form-label">盘点备注</label>
                                    <textarea class="form-control" id="discrepancy_notes" name="discrepancy_notes" 
                                              rows="3" placeholder="请输入盘点过程中发现的问题、差异说明或其他备注信息...">{{ item.discrepancy_notes }}</textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 差异提醒 -->
                        <div class="alert alert-warning d-none" id="discrepancyAlert">
                            <h6><i class="fas fa-exclamation-triangle me-2"></i>发现差异</h6>
                            <div id="discrepancyDetails"></div>
                        </div>
                        
                        <!-- 历史盘点记录 -->
                        {% if item.checked_at %}
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h6 class="mb-0"><i class="fas fa-history me-2"></i>盘点历史</h6>
                                </div>
                                <div class="card-body">
                                    <p><strong>上次盘点：</strong>{{ item.checked_at|date:"Y-m-d H:i" }}</p>
                                    <p><strong>盘点人员：</strong>
                                        {% if item.checked_by %}
                                            {{ item.checked_by.get_full_name|default:item.checked_by.username }}
                                        {% else %}
                                            未知
                                        {% endif %}
                                    </p>
                                    {% if item.discrepancy_notes %}
                                        <p><strong>备注：</strong>{{ item.discrepancy_notes }}</p>
                                    {% endif %}
                                </div>
                            </div>
                        {% endif %}
                        
                        <!-- 操作按钮 -->
                        <div class="d-flex justify-content-between">
                            <a href="{% url 'assets:inventory_plan_detail' item.plan.pk %}" class="btn btn-secondary">
                                <i class="fas fa-arrow-left me-1"></i>返回计划
                            </a>
                            <div>
                                <button type="button" class="btn btn-outline-primary me-2" id="previewBtn">
                                    <i class="fas fa-eye me-1"></i>预览差异
                                </button>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-save me-1"></i>保存盘点结果
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('inventoryCheckForm');
    const discrepancyAlert = document.getElementById('discrepancyAlert');
    const discrepancyDetails = document.getElementById('discrepancyDetails');
    const previewBtn = document.getElementById('previewBtn');
    
    // 系统记录的值
    const systemData = {
        status: '{{ item.system_status }}',
        location: '{{ item.system_location.id|default:"" }}',
        user: '{{ item.system_user.id|default:"" }}',
        department: '{{ item.system_department.id|default:"" }}'
    };
    
    // 检查差异的函数
    function checkDiscrepancies() {
        const physicalStatus = document.getElementById('physical_status').value;
        const physicalLocation = document.getElementById('physical_location').value;
        const physicalUser = document.getElementById('physical_user').value;
        const physicalDepartment = document.getElementById('physical_department').value;
        
        const discrepancies = [];
        
        if (physicalStatus && physicalStatus !== systemData.status) {
            discrepancies.push(`状态差异：系统记录为"{{ item.get_system_status_display }}"，实际为"${document.querySelector('#physical_status option:checked').text}"`);
        }
        
        if (physicalLocation && physicalLocation !== systemData.location) {
            const locationText = document.querySelector('#physical_location option:checked').text;
            discrepancies.push(`位置差异：系统记录为"{% if item.system_location %}{{ item.system_location.name }}{% else %}未设置{% endif %}"，实际为"${locationText}"`);
        }
        
        if (physicalUser && physicalUser !== systemData.user) {
            const userText = document.querySelector('#physical_user option:checked').text;
            discrepancies.push(`使用人差异：系统记录为"{% if item.system_user %}{{ item.system_user.get_full_name|default:item.system_user.username }}{% else %}未分配{% endif %}"，实际为"${userText}"`);
        }
        
        if (physicalDepartment && physicalDepartment !== systemData.department) {
            const deptText = document.querySelector('#physical_department option:checked').text;
            discrepancies.push(`部门差异：系统记录为"{% if item.system_department %}{{ item.system_department.name }}{% else %}未分配{% endif %}"，实际为"${deptText}"`);
        }
        
        if (discrepancies.length > 0) {
            discrepancyDetails.innerHTML = '<ul class="mb-0"><li>' + discrepancies.join('</li><li>') + '</li></ul>';
            discrepancyAlert.classList.remove('d-none');
            
            // 自动设置差异类型
            const discrepancyType = document.getElementById('discrepancy_type');
            if (discrepancyType.value === 'none') {
                if (discrepancies.some(d => d.includes('位置差异'))) {
                    discrepancyType.value = 'location_mismatch';
                } else if (discrepancies.some(d => d.includes('使用人差异'))) {
                    discrepancyType.value = 'user_mismatch';
                } else if (discrepancies.some(d => d.includes('状态差异'))) {
                    discrepancyType.value = 'status_mismatch';
                } else {
                    discrepancyType.value = 'other';
                }
            }
        } else {
            discrepancyAlert.classList.add('d-none');
            document.getElementById('discrepancy_type').value = 'none';
        }
    }
    
    // 监听表单字段变化
    ['physical_status', 'physical_location', 'physical_user', 'physical_department'].forEach(fieldId => {
        document.getElementById(fieldId).addEventListener('change', checkDiscrepancies);
    });
    
    // 预览按钮点击事件
    previewBtn.addEventListener('click', function() {
        checkDiscrepancies();
        if (!discrepancyAlert.classList.contains('d-none')) {
            discrepancyAlert.scrollIntoView({ behavior: 'smooth' });
        } else {
            alert('未发现差异，可以直接保存盘点结果。');
        }
    });
    
    // 表单提交验证
    form.addEventListener('submit', function(e) {
        const physicalStatus = document.getElementById('physical_status').value;
        if (!physicalStatus) {
            e.preventDefault();
            alert('请选择实际状态');
            document.getElementById('physical_status').focus();
            return false;
        }
        
        // 如果有差异但没有填写备注，提醒用户
        if (!discrepancyAlert.classList.contains('d-none')) {
            const notes = document.getElementById('discrepancy_notes').value.trim();
            if (!notes) {
                if (!confirm('发现差异但未填写备注，确定要保存吗？建议填写差异说明。')) {
                    e.preventDefault();
                    document.getElementById('discrepancy_notes').focus();
                    return false;
                }
            }
        }
        
        return confirm('确定要保存盘点结果吗？');
    });
    
    // 页面加载时检查一次差异
    setTimeout(checkDiscrepancies, 500);
});
</script>
{% endblock %}
